package cn.edu.nhic.nhcarsb.interceptor;

import cn.edu.nhic.nhcarsb.entity.R;
import cn.edu.nhic.nhcarsb.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.models.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class AdminInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }
        String token = request.getHeader("token");
        try {
            Integer uid = JwtUtils.verifyAdminTokenAndGetId(token);
            return true;
        } catch (Exception ex) {
            R r = new R();
            r.setCode(403);
            r.setMsg("验证失败！");
            String json = new ObjectMapper().writeValueAsString(r);
            response.setContentType("applicaton/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print(json);
        }
        return false;
    }
}
